import {
  login,
  getUserInfo,
  logout
} from "@/api/auth/auth";
import {
  getToken,
  setToken,
  removeToken
} from "@/util/auth";

const state = {
  token: getToken(), // token
  user: "", // 用户对象
};

const mutations = {
  SET_TOKEN_STATE: (state, token) => {
    state.token = token;
  },
  SET_USER_STATE: (state, user) => {
    state.user = user;
  },
};

const actions = {
  login({
    commit
  }, userInfo) {
    const {
      name,
      password,
    } = userInfo;
    return new Promise((resolve, reject) => {
      login({
          name: name.trim(),
          password: password
        })
        .then((response) => {
          const {
            data
          } = response;
          commit("SET_TOKEN_STATE", data);
          setToken(data);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  getInfo({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((response) => {
          const {
            data
          } = response;
          if (!data) {
            commit("SET_TOKEN_STATE", "");
            commit("SET_USER_STATE", "");
            removeToken();
            resolve();
            reject("Verification failed, please Login again.");
          }
          commit("SET_USER_STATE", data);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then((response) => {
          commit("SET_TOKEN_STATE", "");
          commit("SET_USER_STATE", "");
          removeToken();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};